package com.teamb6.shop.controller.front;

import com.teamb6.shop.domain.Collection;
import com.teamb6.shop.domain.Goods;
import com.teamb6.shop.domain.User;
import com.teamb6.shop.service.CollectionService;
import com.teamb6.shop.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/collection")
public class CollectionController {
    @Autowired
    CollectionService  collectionService;
    //判断用户是否登录，登录后收藏商品
    @RequestMapping("/change")
    @ResponseBody
    public Msg addCollection(Integer goodsid, HttpServletRequest request){
        HttpSession session =request.getSession();
        User user=(User) session.getAttribute("user");
        if (user==null){
            return Msg.fail("请先登录");
        }
        Integer userid=user.getUserid();
        Collection collection=new Collection();
        collection.setUserid(userid);
        collection.setGoodsid(goodsid);
        collection.setCollecttime(new Date());
        int flag = collectionService.changeCollection(collection);
        if (flag==1) return Msg.success("添加收藏成功");
        else if (flag==2) return Msg.success("取消收藏成功");
        else return Msg.fail("操作失败");
    }

    //展示收藏的商品
    @RequestMapping("/list")
    public String showAllCollection(Model model,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if(user==null) return "redirect:/users/login";
        Integer userId=user.getUserid();
        List<Goods> collectionList=collectionService.getAllCollection(userId);
        model.addAttribute("collectionList",collectionList);
        return "collection-list";
    }

    //删除收藏商品
    @RequestMapping("/deleteCollection")
    @ResponseBody
    public Msg deleteCollection( Integer goodsId,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        collectionService.deleteCollection(user.getUserid(),goodsId);
        return Msg.success("取消收藏成功！");
    }



}
